//
//  FileHelper.swift
//  foreign_swift
//
//  Created by hdr on 15-4-14.
//  Copyright (c) 2015年 hdr. All rights reserved.
//

import Foundation

struct FileHelper{
    static func saveFile(var filename:String,data:NSDictionary?){

        filename = getAbsolutePath(filename)

        var fm = NSFileManager.defaultManager()
        if !fm.fileExistsAtPath(filename) {
            if let d = data {
            //文件不存在则创建文件
                fm.createFileAtPath(filename, contents: nil, attributes: nil)
            }else {
                return;
            }
        }
        if data == nil {
            //文件存在，且传进来的内容为空，则删除文件
            fm.removeItemAtPath(filename, error: nil)
        }
    
        data?.writeToFile(filename, atomically: false)
       
    }
    
    static func getFileContent(var filename:String)->String{
        filename = getAbsolutePath(filename)
        var fm = NSFileManager.defaultManager()
        
        if !fm.fileExistsAtPath(filename) {
            return ""
        }
//        NSString(con
        var e = NSErrorPointer();
        var str = NSString(contentsOfFile: filename, encoding: NSUTF8StringEncoding, error: e)!
        return str as String
    }
    
    static func getFilePathWithFileName()->NSString{
        var arr =  NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.UserDomainMask, true)
        var doc = arr[0] as! String
        return doc
    }
    
    static func getAbsolutePath(filename:String) ->String{
        return getFilePathWithFileName().stringByAppendingPathComponent(filename)
    }
}